<template>
    <el-card>
        <el-button type="primary" @click="dialogVisible = true">新建</el-button>

        <template #header>
            <div>
                角色管理
            </div>
        </template>
        <el-table :data="roleData">
            <el-table-column label="ID" prop="id">
            </el-table-column>
            <el-table-column label="角色名称" prop="rolename">
            </el-table-column>
            <el-table-column label="角色状态" prop="state">
                <template #default="{ row }">
                    <el-switch v-model="row.state" :active-value="1" :inactive-value="0"
                        @change="handleChange($event, row.id)">

                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button type="primary" @click="handleEditMenu(row.id,row.menu)">权限</el-button>
                    <el-button type="warning" @click="handleEdit(row)">编辑</el-button>
                    <el-button type="danger" @click="handleDelete(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-row style="height:60px;" align="middle" justify="center">
            <el-pagination background layout="prev, pager, next" :total="total" v-model:page-size="pageSize"
                v-model:current-page="page" @current-change="getdata" />
        </el-row>
        <!-- 弹窗 -->
        <el-dialog v-model="dialogVisible" title="新增" width="500">
            <el-form label-width="80px" :model="addForm" :rules="rules" ref="formIns">
                <el-form-item label="角色名" prop="rolename">
                    <el-input v-model="addForm.rolename"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handlesubmit">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 编辑弹框 -->
        <el-dialog v-model="dialogVisible2" title="编辑" width="500">
            <el-form label-width="80px" :model="editForm" :rules="rules" ref="formIns2">
                <el-form-item label="角色名" prop="rolename">
                    <el-input v-model="editForm.rolename"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible2 = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit2">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 权限弹框 -->
        <el-dialog v-model="dialogVisible3" title="权限" width="500">
            <el-checkbox-group v-model="checkedMenu">
                <el-checkbox  v-for="item in menu" :key="item.id" :value="item.label" :label="item.label">

                </el-checkbox>
            </el-checkbox-group>
            
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible3 = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit3">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>

    </el-card>
</template>
<script setup lang="ts">
// 弹框

const open = () => {
    ElMessageBox.alert('This is a message', 'Title', {
        // if you want to disable its autofocus
        // autofocus: false,
        confirmButtonText: 'OK',
        callback: (action: Action) => {
            ElMessage({
                type: 'info',
                message: `action: ${action}`,
            })
        },
    })
}
import { ref, reactive, onMounted } from 'vue';
import { getRole, addRole, findbyrid, delRole, edtRole, getMenu } from '@/api/api';
import type { FormRules, FormInstance } from "element-plus"
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Action } from 'element-plus'


// 查看
const roleData = ref<RoleData[]>([]);
onMounted(() => {
    getdata();
})
const pageSize = ref(5);
const total = ref(0);
const page = ref(1);
const getdata = async () => {
    const res = await getRole({
        page: page.value,
        limit: pageSize.value
    });
    roleData.value = res.data.data;
    total.value = res.data.total
}
// 新增数据
const addForm = reactive<RoleForm>({
    rolename: ""
});
const rules: FormRules = {
    rolename: { required: true, message: "请输入不重复的角色名", trigger: "blur" }
}
const dialogVisible = ref(false)
const formIns = ref<FormInstance>();
const handlesubmit = async () => {
    formIns.value?.validate(async (valid) => {
        if (valid) {
            const res = await addRole(addForm)
            if (res.data.code === 200) {
                ElMessage.success("修改成功");
                dialogVisible.value = false;
                formIns.value?.resetFields();
                getdata();
            } else {
                ElMessage.error("修改失败")
            }
        }
    })
}
// 删除
const handleDelete = async (id: number) => {
    const res = await findbyrid(id);
    // console.log(res.data)
    if (res.data.code === 201) {
        ElMessage.error("当前角色下有用户，不能删除");

    }
    try {
        await ElMessageBox.confirm(
            '确认删除当前角色吗',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        const res = await delRole(id);
        if (res.data.code === 200) {
            ElMessage.success("删除成功");
            getdata();
        } else {
            ElMessage.error("删除失败");
        }
    } catch (e) {
        ElMessage.info("取消删除")
    }
}
//编辑
const handleChange = async (val: number, id: number) => {
    const res = await edtRole(id, { state: val });
    if (res.data.code === 200) {
        ElMessage.success("修改成功");
    }
}

const dialogVisible2 = ref(false);

const editForm = reactive<RoleForm>({
    rolename: ""
});
const formIns2 = ref<FormInstance>();
let eidtid = 0;
const handleEdit = (body: RoleData) => {
    dialogVisible2.value = true;
    editForm.rolename = body.rolename;
    eidtid = body.id;
}
// 权限
const checkedMenu=ref<string[]>([]);
const menu=ref<MenuData[]>([]);
onMounted(async()=>{
    const res=await getMenu({page:1,limit:20})
    menu.value=res.data.data;
})
const dialogVisible3 = ref(false);
const handleEditMenu = (id: number,menu:string) => {
    
    
    dialogVisible3.value = true;
    checkedMenu.value = JSON.parse(menu)  ;
    eidtid = id;
}
const handleSubmit3 =async () => {
    
    const res=await edtRole(eidtid,{menu:JSON.stringify(checkedMenu.value)})
    if (res.data.code === 200) {
        ElMessage.success("修改成功");
        getdata();
        dialogVisible3.value=false;
    }
}

const handleSubmit2 = () => {
    formIns2.value?.validate(async valid => {
        if (valid) {
            const res = await edtRole(eidtid, editForm)
            if (res.data.code === 200) {
            dialogVisible2.value=false;
            getdata();
            ElMessage.success("修改成功");
        } else {
            ElMessage.error("删除失败");
        }
        }
    })
}
</script>
<style scoped></style>